package com.shujia.spark.sql.test

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions.{explode, lag, round, when}
import org.apache.spark.sql.{Column, DataFrame, SparkSession}

object Test02 {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession
      .builder()
      .appName("test")
      .master("local")
      .getOrCreate()

    val burkDF: DataFrame = spark.read
      .schema("burk STRING,year STRING,tsl01 DOUBLE,tsl02 DOUBLE,tsl03 DOUBLE,tsl04 DOUBLE,tsl05 DOUBLE,tsl06 DOUBLE,tsl07 DOUBLE,tsl08 DOUBLE,tsl09 DOUBLE,tsl10 DOUBLE,tsl11 DOUBLE,tsl12 DOUBLE")
      .csv("data/test.txt")

    burkDF.createOrReplaceTempView("burk")
    /**
      * 2、统计每个公司当月比上年同期增长率
      * 公司代码,年度,月度,增长率（当月收入/上年当月收入 - 1）
      *
      */
    //导入隐式转换
    import spark.implicits._
    //导入spark 所有的函数
    import org.apache.spark.sql.functions._
    /**
      * sql
      */
    spark.sql(
      """
        |select burk,year,mouth,
        |case
        |when p is null
        |then '1'
        |else p
        |end
        |from (
        |select burk,year,mouth,(plc/lastPlc -1)as p
        |from(
        |select burk,year,mouth,plc,lag(plc,1,0) over(partition by mouth,burk order by year) as lastPlc
        |from(
        |select burk,year,explode(map(1,tsl01,2,tsl02,3,tsl03,4,tsl04,5,tsl05,6,tsl06,7,tsl07,8,tsl08,9,tsl09,10,tsl10,11,tsl11,12,tsl12)) as(mouth,plc)
        |from burk
        |) as a)
        |)
        |
      """.stripMargin)
//      .show(1000)
    val m: Column = map(
      expr("1"), $"tsl01",
      expr("2"), $"tsl02",
      expr("3"), $"tsl03",
      expr("4"), $"tsl04",
      expr("5"), $"tsl05",
      expr("6"), $"tsl06",
      expr("7"), $"tsl07",
      expr("8"), $"tsl08",
      expr("9"), $"tsl09",
      expr("10"), $"tsl10",
      expr("11"), $"tsl11",
      expr("12"), $"tsl12"
    )
    burkDF.select($"burk",$"year",explode(m)as Array("mouth","plc"))
      .withColumn("lastPlc",lag($"plc",1,1) over Window.partitionBy($"burk",$"mouth").orderBy($"year"))
      .withColumn("p",round($"plc"/$"lastPlc" -1,6))
      .select($"burk",$"year",$"mouth",$"plc",$"lastPlc",when($"p".isNull,1)otherwise($"p")as "p")
      .show(1000)
  }
}
